<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="饮食名称" prop="dietName">
        <el-input
          v-model="queryParams.dietName"
          placeholder="请输入饮食名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:nutrition:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:nutrition:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:nutrition:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:nutrition:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="nutritionBindingList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        align="center"
        prop="id"
        width="50"
      />
      <el-table-column label="饮食名称" align="center" prop="dietName" />
      <el-table-column
        label="营养成分"
        align="center"
        prop="nutritionNames"
        width="300"
        show-overflow-tooltip
      />
      <el-table-column
        label="录入时间"
        align="center"
        prop="createTime"
        width="160"
        sortable
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="修改时间"
        align="center"
        prop="updateTime"
        width="160"
        sortable
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改人" align="center" prop="updateBy" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Link"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:nutrition:edit']"
            >成分绑定</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:nutrition:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改饮食和营养关联对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="80px"
        v-if="form.id === null"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="进食" name="进食">
            <template #default>
              <el-form-item label="进食名称" prop="eatId">
                <el-select
                  v-model="addForm.eatId"
                  placeholder="请选择进食名称"
                  style="width: 240px"
                >
                  <el-option
                    v-for="eat in eatList"
                    :key="eat.eatId"
                    :label="eat.eatName"
                    :value="eat.eatId"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-tab-pane>
          <el-tab-pane label="饮水" name="饮水">
            <template #default>
              <el-form-item label="饮水名称" prop="waterId">
                <el-select
                  v-model="addForm.waterId"
                  placeholder="请选择饮水名称"
                  clearable
                >
                  <el-option
                    v-for="dict in water_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-form
        ref="nutritionRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="饮食名称" prop="dietName" v-if="form.id !== null">
          <el-input v-model="form.dietName" disabled style="width: 240px" />
        </el-form-item>
        <el-form-item
          label="营养绑定"
          prop="nutritionIds"
          v-if="form.id !== null"
        >
          <el-select
            v-model="form.nutritionIds"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择绑定的营养成分"
            style="width: 240px"
            @change="updateNutritionTable"
          >
            <el-option
              v-for="nutrition in nutritionList"
              :key="nutrition.nutritionId"
              :label="nutrition.nutritionName"
              :value="nutrition.nutritionId"
            />
          </el-select>
        </el-form-item>

        <!-- 新增的表格 -->
        <el-table
          :data="form.ingredients"
          style="width: 100%"
          v-if="form.id !== null"
          class="nutritionBindingTable"
        >
          <el-table-column label="成分名称" prop="nutritionName" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.nutritionName" disabled />
            </template>
          </el-table-column>
          <el-table-column label="成分含量" prop="nutritionNrv" align="center">
            <template #default="scope">
              <el-form-item
                :prop="'ingredients.' + scope.$index + '.nutritionNrv'"
                :rules="rules.nutritionNrv"
              >
                <el-input-number
                  v-model="scope.row.nutritionNrv"
                  :min="0"
                  :precision="2"
                  :step="0.01"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="成分单位" prop="nutritionUnit" align="center">
            <template #default="scope">
              <el-input
                v-model="scope.row.nutritionUnit"
                :placeholder="showUnit(scope.row.nutritionName)"
                disabled
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Nutrition">
import { listNutritionBinding, getNutritionBinding, delNutritionBinding, addNutritionBinding, updateNutritionBinding } from "@/api/manage/nutritionBinding"
import { listNutrition, getNutrition } from "@/api/manage/nutrition"
import { listEat } from "@/api/manage/eat"

const { proxy } = getCurrentInstance()
const { water_type } = proxy.useDict('water_type')

const nutritionBindingList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const activeTab = ref("进食")

const data = reactive({
  form: {
    nutritionIds: null,
    ingredients: []
  },
  addForm: {
  },
  queryParams: {
    dietName: null,
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    nutritionNrv: [
      { required: true, message: "成分含量不能为空", trigger: "blur" }
    ],
  },
  addFormRules: {
  }
})

const { queryParams, form, rules, addForm, addFormRules } = toRefs(data)

const _ingredients = ref([])

/** 更新表格数据 */
function updateNutritionTable () {
  _ingredients.value = form.value.ingredients
  form.value.ingredients = form.value.nutritionIds.map(id => {
    const nutrition = nutritionList.value.find(n => n.nutritionId === id)
    console.log("nutrition", nutrition)
    if (_ingredients.value) {
      const existingIngredient = _ingredients.value.find(ingredient => ingredient.nutritionName === (nutrition ? nutrition.nutritionName : ''))
      console.log("existingIngredient", existingIngredient)
      return {
        nutritionName: nutrition ? nutrition.nutritionName : '',
        nutritionNrv: existingIngredient ? existingIngredient.nutritionNrv : null,
        nutritionUnit: nutrition ? nutrition.nutritionUnit : null
      }
    }
    return {
      nutritionName: nutrition ? nutrition.nutritionName : '',
      nutritionNrv: null,
      nutritionUnit: nutrition ? nutrition.nutritionUnit : null
    }
  })
}

/** 查询饮食和营养关联列表 */
function getList () {
  loading.value = true
  listNutritionBinding(queryParams.value).then(response => {
    nutritionBindingList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel () {
  open.value = false
  reset()
}

// 表单重置
function reset () {
  form.value = {
    id: null,
    assocId: null,
    nutritionIds: null,
    source: null,
    dietName: null,
    ingredients: []
  }
  addForm.value = {
    eatId: null,
    waterId: null
  }
  proxy.resetForm("nutritionRef")
  proxy.resetForm("addFormRef")
}

/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery () {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange (selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd () {
  reset()
  open.value = true
  title.value = "添加营养信息"
}

/** 修改按钮操作 */
function handleUpdate (row) {
  reset()
  const _id = row.id || ids.value
  getNutritionBinding(_id).then(response => {
    form.value = response.data
    if (form.value.nutritionIds && form.value.nutritionIds != '') {
      form.value.nutritionIds = JSON.parse(form.value.nutritionIds)
    }
    if (form.value.ingredients && form.value.ingredients != '') {
      form.value.ingredients = JSON.parse(form.value.ingredients)
    }
    open.value = true
    title.value = "修改营养信息"
  })
}

// 转换数据格式
function exchangeDataForm (data) {
  const selectedEat = eatList.value.find(eat => eat.eatId === data.eatId)
  const selectedWater = water_type.value.find(water => parseInt(water.value) === data.waterId)
  const transformData = []
  if (selectedEat != null) {
    transformData.push({
      assocId: selectedEat.eatId,
      dietName: selectedEat.eatName,
      source: 'tb_eat'
    })
  }
  if (selectedWater != null) {
    transformData.push({
      assocId: parseInt(selectedWater.value),
      dietName: selectedWater.label,
      source: 'tb_drink'
    })
  }
  return transformData
}

/** 提交按钮 */
function submitForm () {
  if (title.value === "添加营养信息") {
    proxy.$refs["addFormRef"].validate(valid => {
      if (valid) {
        if (addForm.value.eatId != null || addForm.value.waterId != null) {
          const data = exchangeDataForm(addForm.value)
          addNutritionBinding(data).then(response => {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          })
        } else {
          proxy.$modal.msgError("请选择进食或饮水")
        }
      }
    })
  } else {
    proxy.$refs["nutritionRef"].validate(valid => {
      const updateForm = {
        id: form.value.id,
        ingredients: JSON.stringify(form.value.ingredients),
        nutritionIds: JSON.stringify(form.value.nutritionIds)
      }
      if (valid) {
        if (form.value.id != null) {
          updateNutritionBinding(updateForm).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        }
      } else {
        proxy.$modal.msgError("您有未填写信息")
      }
    })
  }
}

/** 删除按钮操作 */
function handleDelete (row) {
  const _ids = row.id || ids.value
  const delName = _ids.length >= 1 ? '选中的饮食' : row.dietName
  proxy.$modal.confirm('确定要删除' + delName + '吗？').then(function () {
    return delNutritionBinding(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport () {
  proxy.download('manage/nutritionBinding/export', {
    ...queryParams.value
  }, `nutrition_${new Date().getTime()}.xlsx`)
}

const nutritionList = ref([])

// 获取营养成分列表
function getNutritionList () {
  listNutrition().then(response => {
    nutritionList.value = response.rows
  })
}

const eatList = ref([])

// 获取进食列表
function getEatList () {
  listEat().then(response => {
    eatList.value = unique(response.rows)
  })
}

// 按照进食名称去重
function unique (arr) {
  const res = new Map()
  return arr.filter((arr) => !res.has(arr.eatName) && res.set(arr.eatName, 1))
}

// 显示参考单位
const showUnit = (nutritionName) => {
  const nutrition = nutritionList.value.find(nutrition => nutrition.nutritionName === nutritionName)
  return nutrition.nutritionUnit !== '' ? '参考单位：' + nutrition.nutritionUnit : '请输入成分单位'
}

getList()
getNutritionList()
getEatList()
</script>

<style scoped>
.nutritionBindingTable .el-form-item {
  margin-bottom: 0 !important;
}

:deep(.nutritionBindingTable .el-form-item--default .el-form-item__content) {
  margin-left: 0 !important;
}
</style>